<template>
  <view>
    <!-- 标签页标题 -->
    <view class="tab">
      <view class="tab-item" :class="{active: tab == 0}" @click="changeItem" data-item="0">{{oneTabTitle}}</view>
      <view class="tab-item" :class="{active: tab == 1}" @click="changeItem" data-item="1">播放器</view>
      <view class="tab-item" :class="{active: tab == 2}" @click="changeItem" data-item="2">播放列表</view>
    </view>
    <!-- 内容区域 -->
    <view class="content">
      <swiper class="content-swiper" :current="item" @change="changeTab">
        <swiper-item>
          <music-info v-show="!musicFlag" @data-updated="toMusicList"></music-info>
          <music-list v-show="musicFlag" @data-updated="toMusicInfo"></music-list>
        </swiper-item>
        <swiper-item>
          <music-play></music-play>
        </swiper-item>
        <swiper-item>
          <music-playlist></music-playlist>
        </swiper-item>
      </swiper>
    </view>
    <view class="player">
      <image class="player-cover" :src="playInfo.imgUrl" @click="gotoPlayItem()"></image>
      <view class="player-info" @click="gotoPlayItem()">
        <view class="player-info-title">{{playInfo.title}}</view>
        <view class="player-info-singer">{{playInfo.singer}}</view>
      </view>
      <view class="player-controls" v-if="playInfo.title !== ''">
        <image v-if="!islike" src="../../static/music_icons/like_no.png"
          style="width: 50rpx; height: 50rpx; margin-top: 2rpx;" @click="addToMyList"></image>
        <image v-else src="../../static/music_icons/like_yes.png" style="width: 50rpx; height: 50rpx; margin-top: 2rpx;"
          @click="deleteToMyList"></image>
        <!-- 上一首 -->
        <image src="../../static/music_icons/last.png" @click="musicLast" style="width: 45rpx; height: 45rpx;"></image>
        <!-- 播放 -->
        <image v-if="audioState === 'paused'" src="../../static/music_icons/stop.png" @click="musicPlay"></image>
        <image v-else src="../../static/music_icons/start.png" @click="musicPause"></image>
        <!-- 下一首 -->
        <image src="../../static/music_icons/next.png" @click="musicNext" style="width: 45rpx; height: 45rpx;"></image>
      </view>
    </view>
  </view>
</template>

<script>
  import {
    mapState,
    mapMutations,
    mapGetters
  } from 'vuex'

  export default {
    computed: {
      ...mapState('m_music', ['item', 'playIndex', 'islike', 'musicInfo', 'playInfo', 'savePlayInfo', 'playList',
        'audioCtx', 'audioState', 'songSheetList'
      ]),
    },
    data() {
      return {
        tab: 0,
        waitFlag: false,
        // 推荐音乐和音乐列表显示隐藏的Flag标志
        musicFlag: false,
        //tab 栏第一项显示标题标志
        oneTabTitle: '推荐歌单',
        audioContext: {},
      };
    },
    // 监听事件
    watch: {
      songSheetList(newSongSheetList) {
        if (newSongSheetList == -1) {
          this.oneTabTitle = '我喜欢的音乐'
        } else if (newSongSheetList == -2) {
          this.oneTabTitle = '最近播放'
        } else if (newSongSheetList >= 0 && newSongSheetList <= 5) {
          this.oneTabTitle = '歌单列表'
        } else {
          this.oneTabTitle = '推荐歌单'
        }
      }
    },
    // 音乐播放事件
    onLoad() {
      // 调用方法，获取音乐的数据列表
      this.getMusicInfo()
      this.getPlayInfo()
      // 进入界面时更新播放时长
      if (this.audioState === 'running') {
        this.audioCtx.pause()
        this.audioCtx.play()
      }
    },
    // 音乐播放事件
    onReady: function() {
      this.setAudioCtx()
      var that = this
      // 播放失败检测
      this.audioCtx.onError(function() {
        console.log('播放失败：' + that.audioCtx.src)
      })

      // 播放完成自动换下一曲
      this.audioCtx.onEnded(function() {
        that.automaticMusicNext()
      })
      // 自动更新播放进度
      this.audioCtx.onPlay(function() {})
      this.audioCtx.onTimeUpdate(function() {
        that.playInfo.duration = formatTime(that.audioCtx.duration)
        that.playInfo.currentTime = formatTime(that.audioCtx.currentTime)
        that.playInfo.percent = that.audioCtx.currentTime / that.audioCtx.duration * 100
      })
      // 格式化时间
      function formatTime(time) {
        var minute = Math.floor(time / 60) % 60;
        var second = Math.floor(time) % 60
        return (minute < 10 ? '0' + minute : minute) + ':' + (second < 10 ? '0' + second : second)
      }
    },
    methods: {
      ...mapMutations('m_music', ['updateItem', 'setToMusicList', 'addToPlay', 'setMusic', 'setAudioCtx', 'setState',
        'audioWait', 'updateUserMusicList', 'setPlayInfo'
      ]),
      async getMusicInfo() {
        const {
          data: res
        } = await uni.$http.get('/api/music/musicList')
        // 请求失败
        if (res.meta.status !== 200) return uni.$showMsg()
        // 请求成功
        this.setToMusicList(res.message)
      },
      getPlayInfo() {
        if (this.playList[this.playIndex] !== undefined) {
          this.setPlayInfo(this.playList[this.playIndex])
        }
      },
      // tab 点击事件
      changeItem(e) {
        this.updateItem(e.currentTarget.dataset.item)
      },
      // swiper 滑动事件
      changeTab(e) {
        this.tab = e.detail.current
      },
      // 点击底部播放器左侧跳转到播放器界面
      gotoPlayItem() {
        if (this.Item !== 1 && this.playInfo.title.length !== 0) {
          this.updateItem(1)
        }
      },
      // 音乐播放事件
      musicPlay() {
        if (this.playList.length == 0 && this.playInfo.title <= 0) {
          return uni.$showMsg('歌荒啦，快去添加吧~')
        }
        this.setMusic(this.playIndex)
        this.audioCtx.play()
        this.setState('running')
        this.audioWait()
      },
      // 音乐暂停事件
      musicPause() {
        this.audioCtx.pause()
        this.setState('paused')
      },
      // 音乐上一首事件
      musicLast() {
        if ((this.playList.length == 0 || this.playList.length <= 1 && this.playList[0].title === this.playInfo
            .title)) {
          return uni.$showMsg('歌荒啦，快去添加吧~')
        }
        var index = this.playIndex == 0 ? this.playList.length - 1 : this.playIndex - 1
        this.setMusic(index)
        if (this.audioState === 'running') {
          this.audioCtx.play()
          this.audioWait()
        }
      },
      // 音乐下一首事件
      musicNext() {
        if ((this.playList.length == 0 || this.playList.length <= 1 && this.playList[0].title === this.playInfo
            .title)) {
          return uni.$showMsg('歌荒啦，快去添加吧~')
        }
        var index = this.playIndex >= this.playList.length - 1 ? 0 : this.playIndex + 1
        this.setMusic(index)
        if (this.audioState === 'running') {
          this.audioCtx.play()
          this.audioWait()
        }
      },
      // 自动下一首事件
      automaticMusicNext() {
        var index = this.playIndex >= this.playList.length - 1 ? 0 : this.playIndex + 1
        this.setMusic(index)
        if (this.audioState === 'running') {
          this.audioCtx.play()
          this.audioWait()
        }
      },
      // 点击爱心添加歌曲到我的歌单事件
      async addToMyList() {
        if (this.playInfo.title.length <= 0) {
          return uni.$showMsg('请先选择歌曲！')
        }
        // 准备参数
        var token = uni.getStorageSync('token')
        const music = this.playList[this.playIndex]
        const query = {
          token,
          music,
        }
        const {
          data: res
        } = await uni.$http.post('/api/update/music', query)
        if (res.meta.status !== 200) return uni.$showMsg('操作失败')
        this.updateUserMusicList(res.message)
      },
      // 点击爱心删除我的歌单对应歌曲事件
      async deleteToMyList() {
        if (this.playInfo.title.length <= 0) {
          return uni.$showMsg('请先选择歌曲！')
        }
        // 准备参数
        var token = uni.getStorageSync('token')
        const music = this.playList[this.playIndex]
        const query = {
          token,
          music,
        }
        const {
          data: res
        } = await uni.$http.post('/api/update/music', query)
        if (res.meta.status !== 200) return uni.$showMsg('操作失败')
        this.updateUserMusicList(res.message)
      },
      // 修改推荐音乐和音乐列表显示隐藏的Flag标志
      toMusicList() {
        this.musicFlag = true
      },
      // 修改推荐音乐和音乐列表显示隐藏的Flag标志
      toMusicInfo() {
        this.musicFlag = false
      }
    }
  }
</script>

<style lang="scss">
  page {
    display: flex;
    flex-direction: column;
    background: whitesmoke;
    color: black;
    height: 100%;
  }

  .tab {
    display: flex;

    .tab-item {
      flex: 1;
      font-size: 10pt;
      text-align: center;
      line-height: 72rpx;
      border-bottom: 6rpx solid #ddd;
    }

    .tab-item.active {
      color: #fba007;
      border-bottom-color: #fba007;
    }
  }

  .content {
    flex: 1;

    .content-swiper {
      height: calc(100vh - 112rpx);
    }
  }

  // 底部播放器样式 
  .player {
    display: flex;
    align-items: center;
    position: fixed;
    bottom: 0;
    width: 100%;
    background: whitesmoke;
    border-top: 6rpx solid #eee;
    height: 112rpx;

    .player-cover {
      width: 80rpx;
      height: 80rpx;
      margin-left: 30rpx;
      border-radius: 8rpx;
    }

    .player-info {
      flex: 1;
      font-size: 10pt;
      line-height: 38rpx;
      margin-left: 20rpx;
      margin-right: 20rpx;
      padding-bottom: 8rpx;
      overflow: hidden;
      white-space: nowrap;

      .player-info-title {
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
      }

      .player-info-singer {
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
        color: #888;
      }
    }

    .player-controls {
      display: flex;
      align-items: center;
    }

    .player-controls image {
      width: 55rpx;
      height: 55rpx;
      margin-right: 25rpx;
    }
  }
</style>